<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片信息区 -->
        <el-card>
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon closable></el-alert>
            <el-row>
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader :props="goodsCateProps" v-model="selectCateKeys" :options="cateList"  @change="handleChange" clearable></el-cascader>
                </el-col>
            </el-row>

            <!-- Tab栏切换 -->
            <el-tabs v-model="tabActiveName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="addDialogVisible=true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyParamsData" border stripe>
                        <!-- 展开列 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 标签 -->
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="removeTag(i,scope.row)">{{item}}</el-tag>
                                <!-- 添加信息输入框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.roe)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index" label='#'></el-table-column>
                        <el-table-column label='参数名称' prop="attr_name"></el-table-column>
                        <el-table-column label='操作'>
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editShowDialog(scope.row.attr_id)">修改</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeOldCate(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="addDialogVisible=true">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyParamsData" border stripe>
                        <!-- 展开列 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 标签 -->
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="removeTag(i,scope.row)">{{item}}</el-tag>
                                <!-- 添加信息输入框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.roe)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index" label='#'></el-table-column>
                        <el-table-column label='属性名称' prop="attr_name"></el-table-column>
                        <el-table-column label='操作'>
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editShowDialog(scope.row.attr_id)">修改</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeOldCate(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数、属性对话框 -->
        <el-dialog :title="'添加'+ paramsTitle" :visible.sync="addDialogVisible" width="50%" @close="addCateClose">
            <el-form :model="addForm" status-icon :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="paramsTitle" prop="attr_name">
                    <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addNewCate">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改参数、属性对话框 -->
        <el-dialog :title="'添加'+ paramsTitle" :visible.sync="editDialogVisible" width="50%" @close="editCateClose">
            <el-form :model="editForm" status-icon :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="paramsTitle" prop="attr_name">
                    <el-input v-model="editForm.attr_name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editNewCate">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      //   商品分类列表
      cateList: [],
      // 级联选择器配置对象
      goodsCateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器选择对象的Id
      selectCateKeys: [],
      // 首选Tab栏
      tabActiveName: 'many',
      // 商品参数数据
      manyParamsData: [],
      // 商品属性数据
      onlyParamsData: [],
      // 是否显示添加参数、属性对话框
      addDialogVisible: false,
      // 添加表单对象
      addForm: {
        attr_name: ''
      },
      // 表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入要添加的信息', trigger: 'blur' }]
      },
      // 是否显示修改参数、属性对话框
      editDialogVisible: false,
      // 修改表单对象
      editForm: {},
      // 修改表单验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入要添加的信息', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //   获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取商品分类列表失败！',
          type: 'error'
        })
      }
      this.cateList = res.data
    },
    // 当级联选择框发生改变时
    handleChange() {
      this.getTabData()
    },
    // 当Tab栏发生切换时
    handleTabClick() {
      this.getTabData()
    },
    // 获取Tab栏数据
    async getTabData() {
      // 判断级联选择框是否选中第三级
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyParamsData = []
        this.onlyParamsData = []
        this.getCateList()
      } else {
        const { data: res } = await this.$http.get(`categories/${this.cetaId}/attributes`, { params: { sel: this.tabActiveName } })
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: '获取商品参数列表失败！',
            type: 'error'
          })
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })

        if (this.tabActiveName === 'many') {
          this.manyParamsData = res.data
        } else {
          this.onlyParamsData = res.data
        }
      }
    },
    // 监听键盘回车及失去鼠标焦点
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 进行后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 保存attrvals
    async saveAttrVals(row) {
      // 发起网络请求
      const { data: res } = await this.$http.put(`categories/${this.cetaId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '更新信息失败！',
          type: 'error'
        })
      }
      this.$message({
        showClose: true,
        message: '更新信息成功！',
        type: 'success'
      })
    },
    // 删除tag
    removeTag(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 展示按钮
    showInput(row) {
      row.inputVisible = true
      // $nextTick 当表单元数加载完毕后，执行其中代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加对话框关闭重置
    addCateClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确认，提交新的参数，属性
    addNewCate() {
      this.$refs.addFormRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.post(`categories/${this.cetaId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.tabActiveName })
        if (res.meta.status !== 201) {
          return this.$message({
            showClose: true,
            message: '提交新的信息失败！',
            type: 'error'
          })
        }
        this.$message({
          showClose: true,
          message: '提交新的信息成功！',
          type: 'success'
        })
        this.getTabData()
        this.addDialogVisible = false
      })
    },
    // 显示修改对话框，并根据Id查询相关信息
    async editShowDialog(id) {
      const { data: res } = await this.$http.get(`categories/${this.cetaId}/attributes/${id}`, { params: { attr_sel: this.tabActiveName } })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取改信息失败！',
          type: 'error'
        })
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改对话框关闭重置
    editCateClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确认，修改为新的参数，属性
    editNewCate() {
      this.$refs.editFormRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put(`categories/${this.cetaId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.tabActiveName })
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: '修改失败！',
            type: 'error'
          })
        }
        this.$message({
          showClose: true,
          message: '修改成功！',
          type: 'success'
        })
        this.getTabData()
        this.editDialogVisible = false
      })
    },
    // 点击删除删除旧的参数、属性
    async removeOldCate(id) {
      const removeInfo = await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeInfo !== 'confirm') {
        return this.$message({
          showClose: true,
          message: '已取消删除！',
          type: 'info'
        })
      } else {
        const { data: res } = await this.$http.delete(`categories/${this.cetaId}/attributes/${id}`)
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: '删除失败！',
            type: 'error'
          })
        }
        this.$message({
          showClose: true,
          message: '删除成功！',
          type: 'success'
        })
        this.getTabData()
      }
    }
  },
  computed: {
    //   是否禁用按钮
    isBtnDisable() {
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },
    //  得到分类ID
    cetaId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },
    // 对话框Title按需显示
    paramsTitle() {
      if (this.tabActiveName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.tit_position {
    align-items: center;
}
.el-row,.el-tabs,.el-table{
    margin-top: 20px;
}
.el-tag {
    margin: 8px;
}
.input-new-tag{
    width: 100px,
}
</style>
